package com.mall.utils.encrypt;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

public class AESUtil {


    public static String encrypt(String content, String key) throws Exception {
        String encryptStr = null;

        try {
            Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.decodeBase64(key), "AES");
            aesECB.init(1, secretKeySpec);
            byte[] result = aesECB.doFinal(content.getBytes());
            encryptStr = Base64.encodeBase64String(result);
            return encryptStr;
        } catch (Exception var6) {
            throw var6;
        }
    }

    public static String decrypt(String content, String key) throws Exception {
        String decryptStr = null;

        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.decodeBase64(key), "AES");
            cipher.init(2, secretKeySpec);
            byte[] result = Base64.decodeBase64(content);
            decryptStr = new String(cipher.doFinal(result));
            return decryptStr;
        } catch (Exception var6) {
            throw var6;
        }
    }

    public static String generateKey() throws Exception {
        String genKey = null;

        try {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            keygen.init(128);
            Key key = keygen.generateKey();
            byte[] keyBytes = key.getEncoded();
            genKey = Base64.encodeBase64String(keyBytes);
            return genKey;
        } catch (Exception var4) {
            throw var4;
        }
    }

    public static void main(String[] args) throws Exception {
        //System.out.println(generateKey());
        //System.out.println(encrypt("a","N0QHfV8Pl5VSZQ0nsblgwg=="));
        System.out.println(decrypt("jeIaS00TEzXYPURInkSuCtNjSxFI8DExIZrfrEm759sSmd1kE2iaNeDKKycNigUsBu4JHelzMMWWBXb9nSscsQ==","rt8nRkXz7vLfbaM0ijFKG2hk7z59dKpsn9dseAsJqCH=="));
    }

}
